import { useModel } from '@umijs/max';
import { AUTH_TYPE } from '@/options';

const useAuth = (code: string) => {
  const { initialState } = useModel('@@initialState');
  const roleList: USER_TYPE.RoleList = initialState?.roleList || {};

  const hasAuth = (url: string): boolean => {
    if (!roleList[code]) return false;
    return roleList[code].some((c) => {
      return c.toLowerCase() === url.toLowerCase();
    });
  };
  const listAuth = hasAuth(AUTH_TYPE.LIST);
  const insertAuth = hasAuth(AUTH_TYPE.INSERT);
  const updateAuth = hasAuth(AUTH_TYPE.UPDATE);
  //编辑和详情最多存在一个
  const detailAuth = !updateAuth && hasAuth(AUTH_TYPE.DETAIL);
  const delAuth = hasAuth(AUTH_TYPE.DELETE);
  return {
    roleList,
    hasAuth,
    listAuth,
    insertAuth,
    updateAuth,
    detailAuth,
    delAuth,
  };
};

export default useAuth;
